package com.situ.ymall.admin.controller;


import com.github.pagehelper.PageInfo;
import com.situ.ymall.admin.entity.APIResult;
import com.situ.ymall.admin.entity.Goods;
import com.situ.ymall.admin.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/goods")
@CrossOrigin(origins = {"*"})
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    /**
     * 增加商品
     */
    @PostMapping
    public APIResult insert( @RequestBody Goods goods){
        Goods good = goodsService.insert(goods);


        APIResult apiResult = new APIResult();
        if(good != null){
            apiResult = APIResult.create(good);
        }else {
            apiResult = APIResult.notFound("添加失败");
        }
        return apiResult;
    }
   /**
     * 删除商品
     */
    @DeleteMapping
    public APIResult remove(Integer id){
        Goods goods = goodsService.remove(id);
        APIResult apiResult = new APIResult();
        if (goods != null){
            apiResult = APIResult.ok(goods);
        }else {
            apiResult = APIResult.notFound("删除失败");
        }
        return apiResult;
    }
    /**
     * 修改商品
     */
    @PutMapping
    public APIResult update(@RequestBody Goods goods){
        System.out.println(goods);
        Goods update = goodsService.update(goods);
        return APIResult.create(update);
    }

   /**
     * 查询所有商品
     */
    @GetMapping
    public APIResult select(Integer page, Integer limit ,Goods goods){
        PageInfo pageInfo = goodsService.selectByPage(page, limit, goods);
        APIResult apiResult = new APIResult();
        if (pageInfo == null || pageInfo.getTotal() == 0) {
            return APIResult.notFound("没有数据");
        }else {
            return APIResult.ok(pageInfo);
        }
    }
    /*
        恢复商品
     */
    @RequestMapping("/{id}")
    public APIResult recover(@PathVariable("id") Integer id){
        Goods recover = goodsService.recover(id);
        return APIResult.create(recover);
    }

}
